//
//  RichToolsBarView.swift
//  RichTextEditor
//
//  Created by 李金梁 on 2020/6/23.
//  Copyright © 2020 李金梁. All rights reserved.
//

import UIKit

/*******
 - 尺寸规范:
 - 命名规范: 页面名称_viewName_sizeType
 */
let screen_width = UIScreen.main.bounds.size.width // 屏幕宽度
let screen_height = UIScreen.main.bounds.size.height // 屏幕高度
let screen_nav_height: CGFloat = 44 // 导航高度

public enum RichToolsType : Int {

    case image = 0

    case bold = 1

    case italic = 2

    case underLine = 3

    case deleteLine = 4
    
}

protocol RichToolsBarViewDelegate: NSObjectProtocol {
    
    /// 监控richTools位置变化
    ///
    /// - Parameters:
    ///   - richTools: richTools description
    ///   - form: 位置变化
    func richText(richTools: RichToolsBarView, affineTransform form: CGAffineTransform)
    
    func richText(richTools: RichToolsBarView, toolsType:RichToolsType)

}



class RichToolsBarView: UIView {
    
    public var delegate: RichToolsBarViewDelegate?
    private var imageArray = [(UIImage(named: "BoneIcon.bundle/tupian"), RichToolsType.image),
                               (UIImage(named: "BoneIcon.bundle/B"), RichToolsType.bold),
                               (UIImage(named: "BoneIcon.bundle/I"), RichToolsType.italic),
                               (UIImage(named: "BoneIcon.bundle/u"), RichToolsType.underLine)]
    
    private var selectedImageArray = [(UIImage(named: "BoneIcon.bundle/tupian"), RichToolsType.image),
                                      (UIImage(named: "BoneIcon.bundle/BHOVER"), RichToolsType.bold),
                                      (UIImage(named: "BoneIcon.bundle/IHOVER"), RichToolsType.italic),
                                      (UIImage(named: "BoneIcon.bundle/uHOVER"), RichToolsType.underLine)]
    convenience init() {
        self.init(frame: CGRect(x: 0, y: screen_height - 44, width: screen_width, height: 44))

        NotificationCenter.default.addObserver(self, selector:#selector(keyBoardWillShow(_:)), name:UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(keyBoardWillHide(_:)), name:UIResponder.keyboardWillHideNotification, object: nil)
        
        self.layer.masksToBounds = true
        self.backgroundColor = UIColor.white
        
        let line = UIView(frame: CGRect(x: 0, y: 0, width: screen_width, height: 0.5))
        line.backgroundColor = UIColor.lightGray
        self.addSubview(line)
        
        for i in 0..<self.imageArray.count {
            let button = UIButton(frame: CGRect(x: CGFloat(i) * 50, y: 0, width: 50, height: 44))
            button.setImage(imageArray[i].0, for: UIControl.State.normal)
            button.setImage(selectedImageArray[i].0, for: UIControl.State.selected)
            button.tag = 100 + i
            self.addSubview(button)
            button.addTarget(self, action: #selector(action(button:)), for: UIControl.Event.touchUpInside)
        }
        
        self.addSubview(self.closeBtn)

    }
    
    /// 关闭按钮
    lazy var closeBtn: UIButton = {
        let button = UIButton(frame: CGRect(x: screen_width - 50, y: 0, width: 50, height: 44))
        button.setImage(UIImage.init(named: "BoneIcon.bundle/jianpanxia"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(close), for: .touchUpInside)
        return button
    }()

    
    @objc func action(button: UIButton) {
        //_ = self.subviews.map( { ($0 as? UIButton)?.isSelected = false } )
        button.isSelected = !button.isSelected
        self.delegate?.richText(richTools: self, toolsType:imageArray[button.tag - 100].1)
    }
    
    @objc func close() {
        UIApplication.shared.keyWindow?.endEditing(true)
    }
    
    /// 监视键盘显示
    ///
    /// - Parameter note: note description
    @objc private func keyBoardWillShow(_ note:Notification) {
        let userInfo  = note.userInfo
        let keyBoardBounds = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let duration = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        self.convert(keyBoardBounds, to:nil)
        let deltaY = keyBoardBounds.height
        let animations:(() -> Void) = {
            self.transform = CGAffineTransform(translationX: 0,y: -deltaY)
            self.delegate?.richText(richTools: self, affineTransform: self.transform)
        }
        if duration > 0 {
            let options = UIView.AnimationOptions(rawValue: UInt((userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
            
            UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
            
        } else {
            animations()
        }
    }
    
    
    /// 监视键盘隐藏
    @objc private func keyBoardWillHide(_ note: Notification) {
        let userInfo  = note.userInfo
        let duration = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

        let animations:(() -> Void) = {
            self.transform = CGAffineTransform.identity
            self.delegate?.richText(richTools: self, affineTransform: self.transform)
        }
        if duration > 0 {
            let options = UIView.AnimationOptions(rawValue: UInt((userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
            UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
            
        } else {
            animations()
        }
    }
    
    
    // 销毁
    deinit {
        NotificationCenter.default.removeObserver(self, name:UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIResponder.keyboardWillHideNotification, object: nil)
    }
    
}
